<template>
  <a-modal v-model:open="open" :title="title" :confirm-loading="loading" @ok="submit" @cancel="cancel">
    <a-form :model="form" :rules="rules" :label-col="{ sm: 4 }" ref="formRef">
      <a-form-item label="片区名称" name="name" required>
        <a-input v-model:value.trim="form.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="排序" name="sort" required>
        <a-input-number v-model:value="form.sort" :min="0" :precision="0" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { areaApi } from '@/api/business/data/store-api'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/data/store/store-event-name'

const open = ref(false)
const title = ref('新增仓库')
const loading = ref(false)
interface AreaFormParams {
  id?: number
  name: string
  sort?: number
}
interface AreaFormModalProps {
  title: string
  data: AreaFormParams
}
eventEmitter.on(customEventName.AreaFormModal, (props: AreaFormModalProps) => {
  title.value = props.title
  form.value = _.cloneDeep(defaultForm)
  if (!_.isEmpty(props.data)) {
    const keys = _(form.value).keys().push('id').value()
    form.value = _.pick(props.data, keys) as AreaFormParams
  }
  open.value = true
})

// 提交
const formRef = ref()
const defaultForm = {
  name: '',
  sort: ''
}
const form = ref<AreaFormParams>(_.cloneDeep(defaultForm))
const rules = reactive({
  name: [{ required: true, message: '请输入片区名称', trigger: 'blur' }]
})
function submit() {
  formRef.value.validate().then(async () => {
    const fetchName = form.value?.id ? 'update' : 'create'
    try {
      loading.value = true
      const res = await areaApi[fetchName](form.value)
      message.success(res.msg)
      eventEmitter.emit(customEventName.QueryAreaList)
      open.value = false
    } catch (error) {
      message.error(error.msg)
    } finally {
      loading.value = false
    }
  })
}
function cancel() {
  formRef.value.resetFields()
}
</script>
